/*
 * Copyright (c) 2010-2020 Belledonne Communications SARL.
 *
 * This file is part of linphone-android
 * (see https://www.linphone.org).
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package com.newlink.building.activities.main.settings.fragments

import android.content.Context
import android.os.Bundle
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.Toast
import androidx.core.view.doOnPreDraw
import androidx.lifecycle.ViewModelProvider
import com.newlink.building.R
//import com.vdroid.dooraccess.module_linphone.activities.login.LoginActivity
import com.newlink.building.activities.main.settings.viewmodels.AccountSettingsViewModel
import com.newlink.building.activities.main.settings.viewmodels.AccountSettingsViewModelFactory
import com.newlink.building.activities.navigateToPhoneLinking
import com.newlink.building.databinding.SettingsAccountFragmentBinding
import com.newlink.building.utils.Module_Phone_Event
import com.newlink.building.widget.Module_Phone_CustomAlertDialog
import com.newlink.building.widget.Module_Phone_CustomInputDialog
import org.linphone.core.tools.Log

object InputType {
    const val TYPE_NAME = 0x01
    const val TYPE_OVERTIME = 0x02
    const val TYPE_PASSWORD = 0x03
    const val TYPE_DISPLAY_NAME = 0x04
    const val TYPE_SERVER_ADDR1 = 0x05
    const val TYPE_SERVER_PORT1 = 0x06
    const val TYPE_PROXY_SERVER_ADDR = 0x07
    const val TYPE_PROXY_SERVER_PORT = 0x08
    const val TYPE_USERID = 0x09
}

class AccountSettingsFragment : Module_Phone_GenericSettingFragment<SettingsAccountFragmentBinding>() {
    private lateinit var viewModel: AccountSettingsViewModel

    override fun getLayoutId(): Int = R.layout.settings_account_fragment

    //region create
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        binding.lifecycleOwner = viewLifecycleOwner
        binding.sharedMainViewModel = sharedViewModel

        val identity = arguments?.getString("Identity")
        if (identity == null) {
            Log.e("[Account Settings] Identity is null, aborting!")
            // (activity as MainActivity).showSnackBar(R.string.error)
            goBack()
            return
        }
        Log.e("jake", "AccountSettingsFragment=====$identity=====")
        try {
            viewModel = ViewModelProvider(
                this,
                AccountSettingsViewModelFactory(identity)
            )[AccountSettingsViewModel::class.java]
        } catch (nsee: NoSuchElementException) {
            Log.e("[Account Settings] Failed to find Account object, aborting!")
            goBack()
            return
        }
        binding.viewModel = viewModel

        binding.setBackClickListener { goBack() }

        binding.setSaveClickListener {
            registerSipServer()
            viewModel.updateRegistrationState()
        }

        binding.setNameClickListener {
            showCustomInputDialog(
                resources.getString(R.string.contact_edit_name),
                InputType.TYPE_NAME,
                viewModel.userName.value,
                maxLength = 39
            )
        }

        binding.setPwdClickListener {
            Log.e("jake->", "pswd is ${viewModel.password.value}")

            showCustomInputDialog(
                resources.getString(R.string.account_settings_password_title),
                InputType.TYPE_PASSWORD,
                viewModel.password.value,
                inputHide = context!!.getString(R.string.account_settings_password_hide)
            )
        }

        binding.setUserIdClickListener {
            showCustomInputDialog(
                resources.getString(R.string.account_settings_user_id_title),
                InputType.TYPE_USERID,
                viewModel.userId.value,
            )
        }

        binding.setDisplayNameClickListener {
            showCustomInputDialog(
                resources.getString(R.string.account_settings_display_name_title),
                InputType.TYPE_DISPLAY_NAME,
                viewModel.displayName.value,
                maxLength = 69
            )
        }

        binding.setServer1ClickListener {
            showCustomInputDialog(
                resources.getString(R.string.account_settings_server_address_title),
                InputType.TYPE_SERVER_ADDR1,
                viewModel.domain.value

            )
        }

        binding.setPort1ClickListener {
            showCustomInputDialog(
                resources.getString(R.string.account_settings_server_port_title),
                InputType.TYPE_SERVER_PORT1,
                viewModel.port.value,
                inputType = EditorInfo.TYPE_CLASS_NUMBER

            )
        }

        binding.setProxyServerClickListener {
            showCustomInputDialog(
                resources.getString(R.string.account_settings_proxy_server_title),
                InputType.TYPE_PROXY_SERVER_ADDR,
                viewModel.proxyServer.value

            )
        }

        binding.setProxyPortClickListener {
            showCustomInputDialog(
                resources.getString(R.string.account_settings_proxy_port_title),
                InputType.TYPE_PROXY_SERVER_PORT,
                viewModel.proxyPort.value,
                inputType = EditorInfo.TYPE_CLASS_NUMBER
            )
        }

        binding.setOverTimeClickListener {
            showCustomInputDialog(
                resources.getString(R.string.account_settings_expires_title),
                InputType.TYPE_OVERTIME,
                "${viewModel.expires.value}",
                inputType = EditorInfo.TYPE_CLASS_NUMBER,
                resources.getString(R.string.account_settings_expires_tips)
            )
        }

        sharedViewModel.userLogoutEvent.observe(
            viewLifecycleOwner
        ) {
            it.consume {
                Log.e("jake", "....userLogoutEvent.observe...000")

                viewModel.deleteListener.onClicked()
            }
        }

        viewModel.linkPhoneNumberEvent.observe(
            viewLifecycleOwner
        ) {
            it.consume {
                val authInfo = viewModel.account.findAuthInfo()
                if (authInfo == null) {
                    Log.e("[Account Settings] Failed to find auth info for account ${viewModel.account}")
                } else {
                    val args = Bundle()
                    args.putString("Username", authInfo.username)
                    args.putString("Password", authInfo.password)
                    args.putString("HA1", authInfo.ha1)
                    navigateToPhoneLinking(args)
                }
            }
        }

        viewModel.accountRemovedEvent.observe(
            viewLifecycleOwner
        ) {
            it.consume {

                jumpToHome()
                sharedViewModel.accountRemoved.value = true
//                startActivity(Intent(context, LoginActivity::class.java))
            }
        }

        view.doOnPreDraw {
            // Notifies fragment is ready to be drawn
            sharedViewModel.accountSettingsFragmentOpenedEvent.value = Module_Phone_Event(true)
        }
    }

    override fun onResume() {
        super.onResume()
    }

    private fun registerSipServer() {
        // 修改内容后重新注册用户信息到服务器
        if (viewModel.saveAccountInfo()) {
            Toast.makeText(requireContext(), "保存成功!", Toast.LENGTH_SHORT).show()
            exitPage()
        }
    }

    //endregion

    private fun showCustomInputDialog(
        tittle: String,
        type: Int,
        inputText: String?,
        inputType: Int = EditorInfo.TYPE_CLASS_TEXT,
        inputHide: String = "",
        maxLength: Int = 0
    ) {

        context?.let {
            val customInputDialog = Module_Phone_CustomInputDialog(it)
            customInputDialog.setTitle(tittle).setType(type).setInputText(inputText)
                .setInputHint(inputHide)
                .setMaxLength(maxLength)
                .setInputType(inputType)
                .setNegativeButton(
                    listener = object : Module_Phone_CustomInputDialog.OnClickListener {
                        override fun onClick(type: Int, inputText: String) {
                            customInputDialog.dismiss()
                        }
                    }
                ).setPositiveButton(
                    listener = object : Module_Phone_CustomInputDialog.OnClickListener {
                        override fun onClick(type: Int, inputText: String) {
                            when (type) {
                                InputType.TYPE_NAME -> viewModel.userName.value = inputText
                                InputType.TYPE_OVERTIME -> {
                                    if (inputText.isEmpty()) {
                                        Toast.makeText(
                                            context,
                                            R.string.settings_input_empty_warning,
                                            Toast.LENGTH_SHORT
                                        ).show()
                                        return
                                    }
                                    if (inputText.length > 10 || inputText.toFloat() > 2147483646) {
                                        Toast.makeText(
                                            context,
                                            R.string.settings_input_illegal,
                                            Toast.LENGTH_SHORT
                                        ).show()
                                        return
                                    }
                                    val secondVar = inputText.toInt()
                                    if (secondVar < 30 || secondVar > 2147483646) {
                                        Toast.makeText(
                                            context,
                                            R.string.settings_input_illegal,
                                            Toast.LENGTH_SHORT
                                        ).show()
                                        return
                                    }
                                    viewModel.expires.value =
                                        inputText.toInt()
                                }

                                InputType.TYPE_PASSWORD -> viewModel.password.value = inputText
                                InputType.TYPE_DISPLAY_NAME ->
                                    viewModel.displayName.value =
                                        inputText

                                InputType.TYPE_SERVER_ADDR1 -> viewModel.domain.value = inputText
                                InputType.TYPE_SERVER_PORT1 -> viewModel.port.value = inputText
                                InputType.TYPE_PROXY_SERVER_ADDR -> viewModel.proxyServer.value =
                                    inputText

                                InputType.TYPE_PROXY_SERVER_PORT -> viewModel.proxyPort.value =
                                    inputText

                                InputType.TYPE_USERID -> viewModel.userId.value = inputText
                                else -> {}
                            }
                            customInputDialog.dismiss()
                        }
                    }
                )
            customInputDialog.show()
        }
    }

    override fun goBack() {
        if (viewModel.checkChanged()) {
            showRegisterDialog(context!!)
            return
        }
        exitPage()
    }

    private fun showRegisterDialog(context: Context) {

        val dialog = Module_Phone_CustomAlertDialog(context).apply {
            setTitle(R.string.settings_save_warning_title)
            setContentText(resources.getString(R.string.settings_save_warning_content))
            setPositiveButton(resources.getString(R.string.save_dialog_custom)) {
                this.dismiss()
                viewModel.saveAccountInfo()
                exitPage()
            }
            setNegativeButton(resources.getString(R.string.cancel_dialog_custom)) {
                this.dismiss()
                exitPage()
            }
        }
        dialog.show()
    }

    private fun exitPage() {
        sharedViewModel.hideNavigationBar.value = false
        sharedViewModel.jumpToSettingsPage.value = Module_Phone_Event(true)
    }

    private fun jumpToHome() {
        sharedViewModel.jumpToDialHomePage.value = Module_Phone_Event(true)
        sharedViewModel.hideNavigationBar.value = false
    }
}
